//选择的对象列表的文本
var textObject = "";
//选择的对象列表的Id
var idObject = "";
//已选择标签的数目
var tagsNum = 0;


//点击“确定”后把对话框中选到的对象添加到主页面的文本框中，并关闭对话框
function setSelectedObject() {
    var selectText = $("#selectModal").attr("selectText");
    var text = $("#selectedObject").attr("text");
    var ids = $("#selectedObject").attr("idObject");
    text = text.substr(0, text.length - 1);
    ids = ids.substr(0, ids.length - 1);
    $("#iframe0")[0].contentWindow.setSelectValue(selectText, ids, text); //textId,valueId,valueText
}

//清空数据
function clearObject() {
    var treeObj = $.fn.zTree.getZTreeObj("objectTree");
    if (treeObj != null && treeObj != undefined) {
        //取消选中的节点
        var node = treeObj.getSelectedNodes();
        treeObj.cancelSelectedNode(node[0]);
        textObject = "";
        idObject = "";
        //$("#object").html("");
        $("#selectedObject").attr("text", textObject);
        $("#selectedObject").attr("idObject", idObject);
        $("#searchObject").attr("value", "");
        tagsNum = 0;
        //清空input中的标签
        $('#selectedObject').importTags('');
    }
}

//初始化tag标签
function tagIni() {
    $("#selectedObject").tagsInput({
        width: 250,
        height: 380,
        'defaultText': "",
        //删除标签时的回调函数
        'onRemoveTag': function (tag) {
            var text = $("#selectedObject").attr("text");
            var length = text.length;
            var lengthTag = tag.length;
            var n = text.indexOf(tag);
            var arr = text.split(",");
            text = text.substr(0, n) + text.substr(n + lengthTag + 1, length);
            $("#selectedObject").attr("text", text);
            textObject = text;

            var indexId = arr.indexOf(tag);
            var selectIds = $("#selectedObject").attr("idObject");
            var arrId = selectIds.split(",");
            selectIds = "";
            for (var index = 0; index < arrId.length - 1; index++) {
                if (index != indexId) {
                    selectIds += arrId[index] + ",";
                }
            }
            idObject = selectIds;
            $("#selectedObject").attr("selectIds", idObject);
            tagsNum--;
        }
    });
}

//关闭窗口
function closeWin() {
    $("#iframe0")[0].contentWindow.closeWin();
}


var key;
var lastValue = "", nodeList = [], fontCss = {};

//结构树的初始化(单选)
var settingObject = {
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        onClick: zTreeOnClick
    }
};
//结构树的初始化(多选)
var settingObjectMore = {
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        onClick: zTreeOnClickMore
    }
};


function createTreeByUrlWithDefault(treeId, defaultid, oneOrMore, url) {
    var zNodes;
    var treeObjectObj;
    $.ajax({
        url: url,
        type: 'get',
        cache: false,
        dataType: "json", //可以是text，如果用text，返回的结果为字符串；如果需要json格式的，可是设置为json
        success: function (data) {
            zNodes = data;
            $.fn.modal.Constructor.prototype.enforceFocus = function () {
            };
            if (zNodes.status == "ok") {
                //$.fn.zTree.init($("#userTree"), settingUser, zNodes.rows);
                //选择的对象为单选
                if (oneOrMore == 1) {
                    $.fn.zTree.init($("#" + treeId), settingObject, zNodes.rows);
                }
                else {
                    $.fn.zTree.init($("#" + treeId), settingObjectMore, zNodes.rows);
                }
                treeObjectObj = $.fn.zTree.getZTreeObj(treeId);
                //折叠所有节点
                treeObjectObj.expandAll(false);
                //打开根节点
                //var root = treeObjectObj.getNodeByParam("id", "shandongbowuguan", null);
                //treeObjectObj.expandNode(root);
                //定位到当前用户的所属部门
//                    var orgNodeObject = treeObjectObj.getNodeByParam("id",orgId,null);
//                    treeObjectObj.selectNode(orgNodeObject);
//                    treeObjectObj.expandNode(orgNodeObject,true,true,true);
//                    treeObjectObj.updateNode(orgNodeObject);
                //为选中的节点设置触发点击事件
                $(".curSelectedNode").trigger("click");
            }
        },
        error: function (msg) {
            alert("失败");
        }
    });
}

function createTreeByUrl(oneOrMore, url, modelText, selectText) {
    var zNodes;
    var treeObjectObj;
    $.ajax({
        url: url,
        type: 'get',
        cache: false,
        dataType: "json", //可以是text，如果用text，返回的结果为字符串；如果需要json格式的，可是设置为json
        success: function (data) {
            zNodes = data;
            $.fn.modal.Constructor.prototype.enforceFocus = function () {
            };
            //zNodes.rows = [{"id":1,"name":"1text","children":[{"id":2,"name":"2text"}]}];
            if (zNodes.status == "OK") {
                //$.fn.zTree.init($("#userTree"), settingUser, zNodes.rows);
                //选择的对象为单选
                if (oneOrMore == 1) {
                    $.fn.zTree.init($("#objectTree"), settingObject, zNodes.rows);
                }
                else {
                    $.fn.zTree.init($("#objectTree"), settingObjectMore, zNodes.rows);
                }
                treeObjectObj = $.fn.zTree.getZTreeObj("objectTree");
                //折叠所有节点
                treeObjectObj.expandAll(false);
                //为选中的节点设置触发点击事件
                $(".curSelectedNode").trigger("click");

                $("#iframe0")[0].contentWindow.showWin(url, modelText, selectText, oneOrMore);
            }
        },
        error: function (msg) {
            alert("失败");
        }
    });
}


/*
 * 点击回调事件(单选)
 * treeId:结构树ID
 * treeNode:结构树上被点击的节点ID
 */
function zTreeOnClick(event, treeId, treeNode) {
    //把选中的对象转化成标签
    //if ($('#selectedObject').tagExist(treeNode.name)) {
        //alertFunc("请不要重复选择！");
    //}
    //else {
        if (tagsNum >= 1) {
            //alertFunc("只能选择一项！");
            var textobjss = textObject.split(',');
            for(var indexkey=0;indexkey<textobjss.length;indexkey++){
                textobjs = textobjss[indexkey];
                if(textobjs!=null && textobjs!=""){
                    //console.log(textobjs);
                    $('#selectedObject').removeTag(textobjs);
                    $('#selectedObject').removeAttr("text");
                    $('#selectedObject').removeAttr("idObject");
                }
            }
            $('#selectedObject').addTag(treeNode.name);
            textObject += treeNode.name + ",";
            idObject += treeNode.id + ",";
            $("#selectedObject").attr("text", treeNode.name);
            $("#selectedObject").attr("idObject", treeNode.id);
            tagsNum++;
        }
        else {
            $('#selectedObject').addTag(treeNode.name);
            textObject += treeNode.name + ",";
            idObject += treeNode.id + ",";
            $("#selectedObject").attr("text", textObject);
            $("#selectedObject").attr("idObject", idObject);
            tagsNum++;
        }
    //}
};

/*
 * 点击回调事件(多选)
 * treeId:结构树ID
 * treeNode:结构树上被点击的节点ID
 */
function zTreeOnClickMore(event, treeId, treeNode) {
    //把选中的对象转化成标签
    if ($('#selectedObject').tagExist(treeNode.name)) {
        alertFunc("请不要重复选择！");
    }
    else {
        $('#selectedObject').addTag(treeNode.name);
        textObject += treeNode.name + ",";
        idObject += treeNode.id + ",";
        // idObject = treeNode.id;
        tagsNum++;
    }
    $("#selectedObject").attr("text", textObject);
    $("#selectedObject").attr("idObject", idObject);
};

//搜索变色
function getFontCss(treeId, treeNode) {

    return (!!treeNode.highLight) ? {color: "#A60000", "font-weight": "bold"} : {
        color: "#333",
        "font-weight": "normal"
    };
}

function focusKey(e) {
    if (key.hasClass("empty")) {
        key.removeClass("empty");
    }
}
function blurKey(e) {
    if (key.get(0).value === "") {
        key.addClass("empty");
    }
}

//搜索节点，不使用模糊，使用全匹配，当然也可以使用节点ID，文字，模糊查询所有节点，也很简单，不做叙述，类似下面，只是调用方法不同
function searchNode(treeId) {
    var zTree = $.fn.zTree.getZTreeObj(treeId);
    updateNodes(false, treeId);
    var value = $.trim(key.get(0).value);
    if (value != "") {
        var keyType = "name";
        nodeList = zTree.getNodesByParam(keyType, value);
        updateNodes(true, treeId);
    }

}
//更新节点，使其高亮显示，加了展开节点，达到了定位的效果
function updateNodes(highLight, treeId) {
    var zTree = $.fn.zTree.getZTreeObj(treeId);
    for (var i = 0, l = nodeList.length; i < l; i++) {
        nodeList[i].highLight = highLight;
        //定位到节点并展开
        zTree.selectNode(nodeList[i]);
        zTree.expandNode(nodeList[i]);
        zTree.updateNode(nodeList[i]);
    }
}

//treeId为树的Id，searchText为搜索框的Id
function search(treeId, searchText) {
    key = $("#" + searchText);
    key.bind("focus", focusKey)
        .bind("blur", blurKey);

    $("#" + searchText).keydown(function (e) {
        if (e.keyCode == 13) {
            searchNode(treeId);
            e.keyCode = 0;
            window.event.keyCode = 0;
            e.preventDefault();
            return;
        }
    });
    $("#searchBtn").click(function () {
        searchNode(treeId);
    });
}


//加载霍萨分类节点(单选)
var settingForSingleHs = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: 0,
            isParent: "isParent",
        }
    },
    callback: {
        beforeExpand: beforeExpand,
        onAsyncError: onAsyncError,
        onClick: zTreeOnClick,
        onExpand: onExpandForHs
    }
};

//加载霍萨分类节点(多选)
var settingForMultipleHs = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: 0,
            isParent: "isParent",
        }
    },
    callback: {
        beforeExpand: beforeExpand,
        onAsyncError: onAsyncError,
        onClick: zTreeOnClickMore,
        onExpand: onExpandForHs
    }
};


//加载霍萨分类节点(单选)
var settingForSingleMj = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: 0,
            isParent: "isParent",
        }
    },
    callback: {
        beforeExpand: beforeExpand,
        onAsyncError: onAsyncError,
        onClick: zTreeOnClick,
        onExpand: onExpandForMj
    }
};

//加载霍萨分类节点(多选)
var settingForMultipleMj = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId",
            rootPId: 0,
            isParent: "isParent",
        }
    },
    callback: {
        beforeExpand: beforeExpand,
        onAsyncError: onAsyncError,
        onClick: zTreeOnClickMore,
        onExpand: onExpandForMj
    }
};

function createTree(oneOrMore, ModelType, modelText, selectText) {
    var treeObjectObj;
    var url;
    if (ModelType == 'Hs') {
        url = "MbXtglBaseTableServlet.getOneLevelData.do?tn=mb_gy_hsfl";
    } else if (ModelType == 'Mj') {
        url = "MbXtglBaseTableServlet.getOneLevelData.do?tn=mb_gy_mjfl"
    } else {
        url = "MbXtglBaseTableServlet.getPeersDataForZtree.do?tn=mb_gy_cz"
    }
    $.ajax({
            url: url, //url  action是方法的名称
            data: {id: 0},
            type: 'Post',
            dataType: "json",
            success: function (data) {
                if (data.status == "OK") {
                    $.fn.modal.Constructor.prototype.enforceFocus = function () {
                    };
                    if (ModelType == 'Hs') {
                        if (oneOrMore == 1) {
                            $.fn.zTree.init($("#objectTree"), settingForSingleHs, eval(data.rows));
                        } else {
                            $.fn.zTree.init($("#objectTree"), settingForMultipleHs, eval(data.rows));
                        }
                    } else if (ModelType == 'Mj') {
                        if (oneOrMore == 1) {
                            $.fn.zTree.init($("#objectTree"), settingForSingleMj, eval(data.rows));
                        } else {
                            $.fn.zTree.init($("#objectTree"), settingForMultipleMj, eval(data.rows));
                        }
                    } else if (ModelType == 'Cz') {
                        if (oneOrMore == 1) {
                            $.fn.zTree.init($("#objectTree"), settingObject, eval(data.rows));
                        } else {
                            $.fn.zTree.init($("#objectTree"), settingObjectMore, eval(data.rows));
                        }
                    }
                    treeObjectObj = $.fn.zTree.getZTreeObj("objectTree");
                    //折叠所有节点
                    treeObjectObj.expandAll(false);
                    //为选中的节点设置触发点击事件
                    $(".curSelectedNode").trigger("click");
                    $("#iframe0")[0].contentWindow.showWin(url, modelText, selectText, oneOrMore);
                }
            },
            error: function (msg) {
                alert(" 数据加载失败！" + msg);
            }
        }
    );
}


function beforeExpand(treeId, treeNode) {
    if (!treeNode.isAjaxing) {
        return true;
    } else {
        alert("zTree 正在下载数据中，请稍后展开节点。。。");
        return false;
    }
}


function onAsyncError() {
    alert(" 数据加载失败");
}


function onExpandForHs(event, treeId, treeNode) {
    // 判断是否父节点
    if (treeNode.isParent) {
        //alert("treeId自动编号：" + treeNode.tId + ", 节点id是：" + treeNode.id + ", 节点文本是：" + treeNode.name);
        $.ajax({
            url: "MbXtglBaseTableServlet.getOneLevelData.do?tn=mb_gy_hsfl",//请求的action路径
            data: {"id": treeNode.id},
            type: 'Post',
            dataType: "json",
            error: function () {//请求失败处理函数
                alert('请求失败');
            },
            success: function (data) { //添加子节点到指定的父节点
                var jsondata = eval(data.rows);
                if (jsondata == null || jsondata == "") {
                    //末节点的数据为空   所以不再添加节点  这里可以根据业务需求自己写
                    //$("#treeFrame").attr("src",treeNode.url);
                }
                else {
                    var treeObj = $.fn.zTree.getZTreeObj("objectTree");
                    //treeNode.halfCheck = false;
                    var parentZNode = treeObj.getNodeByParam("id", treeNode.id, null);//获取指定父节点
                    newNode = treeObj.addNodes(parentZNode, jsondata, false);
                }
            }
        })
    }
}


function onExpandForMj(event, treeId, treeNode) {
    // 判断是否父节点
    if (treeNode.isParent) {
        //alert("treeId自动编号：" + treeNode.tId + ", 节点id是：" + treeNode.id + ", 节点文本是：" + treeNode.name);
        $.ajax({
            url: "MbXtglBaseTableServlet.getOneLevelData.do?tn=mb_gy_mjfl",//请求的action路径
            data: {"id": treeNode.id},
            type: 'Post',
            dataType: "json",
            error: function () {//请求失败处理函数
                alert('请求失败');
            },
            success: function (data) { //添加子节点到指定的父节点
                var jsondata = eval(data.rows);
                if (jsondata == null || jsondata == "") {
                    //末节点的数据为空   所以不再添加节点  这里可以根据业务需求自己写
                    //$("#treeFrame").attr("src",treeNode.url);
                }
                else {
                    var treeObj = $.fn.zTree.getZTreeObj("objectTree");
                    //treeNode.halfCheck = false;
                    var parentZNode = treeObj.getNodeByParam("id", treeNode.id, null);//获取指定父节点
                    newNode = treeObj.addNodes(parentZNode, jsondata, false);
                }
            }
        })
    }
}

